package com.sunnybear.framework.tools;

import com.sunnybear.framework.tools.log.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  2018/7/23.
 */
public class GlobalHelper {

    /**
     * 全局缓存数据
     */
    public static final String KEY_GLOBAL_VALUES = "key_global_values";

    private GlobalHelper() {
    }

    public static GlobalHelper getInstance() {
        return new GlobalHelper();
    }

    /**
     * 缓存数据
     *
     * @param key   key
     * @param value 数据
     * @param <T>   类型
     */
    public <T> void insert(String key, T value) {
        List<String> keys = PreferenceHelper.getValue(KEY_GLOBAL_VALUES, new ArrayList<String>());
        if (!keys.contains(key)) {
            keys.add(key);
            PreferenceHelper.insert(KEY_GLOBAL_VALUES, keys);
        }
        PreferenceHelper.insert(key, value);
    }

    /**
     * 获得缓存数据
     *
     * @param key key
     * @param <T> 类型
     * @return 缓存数据
     */
    public <T> T getValue(String key, T defaultValue) {
        return PreferenceHelper.getValue(key, defaultValue);
    }

    /**
     * 根据key删除缓存数据
     *
     * @param key key
     */
    public void remove(String key) {
        List<String> keys = PreferenceHelper.getValue(KEY_GLOBAL_VALUES, new ArrayList<String>());
        if (keys.contains(key)) {
            keys.remove(key);
            PreferenceHelper.remove(key);
            PreferenceHelper.insert(KEY_GLOBAL_VALUES, keys);
        }
    }


    /**
     * 清空缓存数据
     */
    public void clear() {
        try {
            List<String> keys = PreferenceHelper.getValue(KEY_GLOBAL_VALUES, new ArrayList<String>());
            for (String key : keys) {
                PreferenceHelper.remove(key);
            }
        } catch (Exception e) {
            Logger.e(e);
        }
        PreferenceHelper.remove(KEY_GLOBAL_VALUES);
    }

}
